﻿using AutoMapper.Internal.Mappers;
using IdentityModel.Client;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using Volo.Abp.Identity;
using Volo.Abp.ObjectMapping;

namespace Himp.Platform
{
    /// <summary>
    /// 
    /// </summary>
    public class LoginManager : DomainService
    {
        public const string DEFAULT_GRANTTYPE = "password";
        public const string DEFAULT_CLIENTID = "Platform_App";
        public const string DEFAULT_SCOPE = "Platform";
        public const string HEADER_TENANT = "__tenant";

        //private readonly IRepository<PsnInfo, Guid> _psnInfoRepository;
        private readonly IRepository<Organ, Guid> _organRepository;

        /// <summary>
        /// 
        /// </summary>
        private readonly IHttpClientFactory _httpClientFactory;

        /// <summary>
        /// 
        /// </summary>
        public SignInManager<Volo.Abp.Identity.IdentityUser> SignInManager { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpClientFactory"></param>
        /// <param name="organRepository"></param>
        /// <param name="psnInfoRepository"></param>
        public LoginManager(IHttpClientFactory httpClientFactory
            , IRepository<Organ, Guid> organRepository)
        {
            _httpClientFactory = httpClientFactory;
            _organRepository = organRepository;
        }

        public async Task<Tuple<string, int>> RequestId4(string authServer, string userName, string password)
        {
            var loginResult = await GetLoginResultAsync(userName, password);

            if (loginResult)
            {

                var client = _httpClientFactory.CreateClient(nameof(LoginManager));
                var request = new PasswordTokenRequest
                {
                    Address = authServer,
                    GrantType = DEFAULT_GRANTTYPE,
                    ClientId = DEFAULT_CLIENTID,
                    Scope = DEFAULT_SCOPE,
                    UserName = userName,
                    Password = password,
                };

                if (CurrentTenant.Id != null)
                {
                    request.Headers.Add(HEADER_TENANT, CurrentTenant.Id?.ToString());
                }

                var tokenResponse = await client.RequestPasswordTokenAsync(request);

                if (tokenResponse.IsError)
                {
                    throw new UserFriendlyException(message: "获取token失败！");
                }

                return new Tuple<string, int>(tokenResponse.AccessToken, tokenResponse.ExpiresIn);
            }
            else
            {
                throw new UserFriendlyException(message: "用户名或者密码错误！");
            }
        }

        //public async Task<Tuple<PsnInfo, List<OrganInfo>>> GetLoginedExtendInfo(Guid userId)
        //{
        //    var psnInfoQuery = await _psnInfoRepository.GetQueryableAsync();
        //    var psnInfo = psnInfoQuery.FirstOrDefault(s => s.UserId == userId);
        //    var organs = await _organRepository.GetListAsync();

        //    return new Tuple<PsnInfo, List<OrganInfo>>(psnInfo, organs);
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<bool> GetLoginResultAsync(string userName, string password)
        {
            var loginResult = await SignInManager.PasswordSignInAsync(userName, password, false, false);
            return loginResult.Succeeded;
        }
    }
}
